<template>
	<view class="contain">
		<view class="title">
			<view style="overflow: hidden;width: 160rpx; height: 160rpx;border-radius: 40rpx;">
				<image src="https://xgr.oss-cn-hangzhou.aliyuncs.com/icon/WechatIMG2024121214101.jpg" mode=""
					style="width: 160rpx; height: 160rpx;"></image>
			</view>
			<view style="margin-left: 40rpx;">
				蓝领兄弟专属福利
				<br />
				扫码入群领好礼
			</view>
		</view>
		<view class="tip">
			<view class="t1">
				幸运抽奖
			</view>
			<view @click="openDoc(5)">
				抽奖规则
			</view>
		</view>
		<view class="prizedraw">
			<view v-for="(item, index) in prize" :key="item.id" class="prize-item"
				:class="{ active: activeIndex === index }">
				<view style="padding: 15rpx;">
					<image :src="item.prizeIcon" mode="" style="width: 100rpx;height: 100rpx;"></image>
				</view>
				<view class="">
					{{ item.prizeName }}
				</view>
			</view>
		</view>
		<view class="stbtn">
			<u-button type="error" text="开始抽奖" shape="circle" @click="startDraw()"></u-button>
		</view>
		<view class="smtip">
			仅有一次抽奖机会
		</view>
		<view class="tip2">
			<view class="t1">
				<view class="" style="font-size: 34rpx;">
					中奖记录
				</view>
				<view @click="reload()">
					<u-icon name="reload" size="20"></u-icon>
				</view>
			</view>
			<view class="t2" v-for="(item,index) in prizeresult":key='item.id'>
				<span>{{item.prizeGift}}</span><span>{{item.createTime}}</span><span>{{item.userName.substr(0, 3)}}****{{item.userName.substr(7)}}</span>
			</view>
		</view>
		<view v-if="prizeresult.length>=1" class="" style="float: right;margin-top: 20rpx;margin-right: 30rpx; color: #007aff;" @click="gogroup()">
			联系客服兑奖 >
		</view>
		
		<u-popup :show="showprize" :round="10" mode="center" @close="close"
			customStyle="width:80%;overflow: hidden;background-color:#f3f4f6" closeOnClickOverlay closeable>
			<view class="upop">
				<p v-if="showprize">尊敬的用户:{{prizeresult[0].userName.substr(0, 3)}}****{{prizeresult[0].userName.substr(7)}}</p>
				<p style="color: #555555;">恭喜您抽到： <span style="color: #007aff;">{{prizeresult[0].prizeGift}}</span></p>
				<p>添加客服微信凭此 <span style="color: #000000; font-weight: bold;">页面截图</span>兑换奖品</p>
				<view style="display: flex;justify-content: center;margin-top: 20rpx;">
					<!-- <image :show-menu-by-longpress="true"
						src="https://xgr.oss-cn-hangzhou.aliyuncs.com/WechatIMG983.jpg" mode="widthFix"
						style="width: 70%;border-radius: 20rpx;"></image> -->
						<u-button type="primary" @click="gogroup()">点击联系客服兑奖</u-button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="showerror" :round="10" mode="center"
			customStyle="width:80%;overflow: hidden;background-color:#f3f4f6">
			<view class="upop">
				
				请从天下工人相关群内链接进入此页面
				<!-- <p style="text-align: center;">长按保存二维码</p>
				<view style="display: flex;justify-content: center;margin-top: 20rpx;">
					<image :show-menu-by-longpress="true"
						src="https://xgr.oss-cn-hangzhou.aliyuncs.com/WechatIMG966.jpg" mode="widthFix"
						style="width: 70%;border-radius: 20rpx;"></image>
				</view> -->
				<view style="margin-top: 20rpx;display: flex;">
					<u-button @click="goback()">返回</u-button>
					<u-button type="primary" @click="gogroup1()">加入群聊</u-button>
				</view>
				
			</view>
		</u-popup>
	</view>

</template>

<script>
	import Index from '@/common/index-model.js'
	let index = new Index();
	let that = null;
	export default {
		data() {
			return {
				showerror:false,
				iv: '', //加密信息算法
				encryptedData: '', //加密信息
				showprize: false,
				prize: [],
				prizeresult: '',
				presult: 1914632740408225793, // 中奖结果
				activeIndex: -1, // 当前高亮的奖品索引
				drawInterval: null, // 抽奖动画的计时器
				drawSpeed: 100, // 初始动画速度
				isDrawing: false, // 是否正在抽奖
				drawSequence: [], // 抽奖顺序序列
				drawStepCount: 0, // 当前动画步数
				targetIndex: 0, // 目标奖品的索引
				targetStep: 0 // 目标步数
			}
		},
		onLoad(opt) {
			const enterOptions = uni.getEnterOptionsSync();
			console.log("进入", enterOptions)
			this.getGroupInfo();
			this.getprizelist()
			this.getprizeresult()
			that = this;
			uni.showShareMenu({
				withShareTicket: true,
				menus: ["shareAppMessage"],
			})
			if (!uni.getStorageSync('token')) {
				index.show_tips('请先登录')
				setTimeout(() => {
					index.navigate_to('../../pagesC/login/login');
					//index.navigate_back(1)
				}, 300)
			} else {

			}
		},
		onShow() {
			this.getprizeresult()
		},
		onShareAppMessage() {
			return {
				title: "蓝领兄弟专属福利，扫码入群领好礼",
				path: "pages/prizeDraw/prizeDraw",
				imageUrl: 'https://xgr.oss-cn-hangzhou.aliyuncs.com/promotion_group_award.jpg'
			};
		},
		methods: {
			//加群
			gogroup1(){
				// #ifdef MP-WEIXIN
				      if (typeof wx.openCustomerServiceChat === 'function') {
				        wx.openCustomerServiceChat({
				          extInfo: { url: "https://work.weixin.qq.com/kfid/kfce7527a080d0f7871" },
				          corpId: "wwa7dc6cde2804f45d",
				          success(res) { console.log("接入成功", res) },
				          fail(err) { 
				            console.error("失败", err);
				            uni.showToast({ title: "请升级微信版本", icon: "none" });
				          }
				        });
				      } else {
				        uni.showToast({ title: "当前微信版本过低", icon: "none" });
				      }
					  // #endif
			},
			//兑奖
			gogroup(){
				// #ifdef MP-WEIXIN
				      if (typeof wx.openCustomerServiceChat === 'function') {
				        wx.openCustomerServiceChat({
				          extInfo: { url: "https://work.weixin.qq.com/kfid/kfc9365506402a0bf76" },
				          corpId: "wwa7dc6cde2804f45d",
				          success(res) { console.log("接入成功", res) },
				          fail(err) { 
				            console.error("失败", err);
				            uni.showToast({ title: "请升级微信版本", icon: "none" });
				          }
				        });
				      } else {
				        uni.showToast({ title: "当前微信版本过低", icon: "none" });
				      }
					  // #endif
			},
			goback(){
				index.switch_tab("/pages/index/index")
			},
			//获取抽奖结果
			getprizeresult() {
				index.getPublicUserMember({}, '/apclient/appUserPrizeDrawRecord/userPrizeDraw/1', 'get', res => {
					if (res.data.code == 200 && res.data.success) {
						this.prizeresult = res.data.result
						console.log("结果", this.prizeresult)
					} else {
						index.show_tips(res.data.message);
						if(res.data.message == 'Token失效，请重新登录!'){
							index.navigate_to('../../pagesC/login/login')
						}
						return
					}
				})
			},
			//获取奖品列表
			getprizelist() {
				index.getPublicMember({}, '/apclient/appUserPrizeDrawRecord/jackpotInfo/1', 'get', res => {
					if (res.data.code == 200 && res.data.success) {
						this.prize = res.data.result.options
						console.log(this.prize)
					} else {
						index.show_tips(res.data.message);
						return
					}
				})
			},
			//获取群加密信息
			getGroupInfo() {
				// 判断接口是否可用
				if (wx.getGroupEnterInfo) {
					wx.getGroupEnterInfo({
						needGroupOpenID: true, // 必填参数
						success: (res) => {
							this.iv = res.iv
							this.encryptedData = res.encryptedData
							console.log('群信息:', this.iv, this.encryptedData);
						},
						fail: (err) => {
							this.showerror = true
							console.error('获取失败:', err);
						}
					});
				} else {
					// 兼容低版本
					uni.showModal({
						title: '提示',
						content: '您的微信版本过低，请升级后使用'
					});
				}
			},
			close() {
				this.showprize = false
			},
			reload() {
				this.getprizeresult()
			},
			openDoc(type) {
				index.navigate_to('../../pagesC/login/xieyi?type=' + type)
			},
			//抽奖按钮
			startDraw() {
				if (!uni.getStorageSync('token')) {
					index.show_tips('请先登录')
					setTimeout(() => {
						index.navigate_to('../../pagesC/login/login');
						//index.navigate_back(1)
					}, 300)
					return
				}
				if (this.isDrawing) return; // 如果正在抽奖，不允许重复点击
				
				index.getPublicUserMember({
					encryptedData: this.encryptedData,
					iv: this.iv,
					type: 1
				}, '/apclient/appUserPrizeDrawRecord/signUpPrizeDraw', 'post', res => {
					if (res.data.code == 200 && res.data.success) {
						console.log(res.data)
						this.presult = res.data.result.prizeOptionId

						

						this.isDrawing = true;
						this.activeIndex = -1;
						this.drawStepCount = 0;
						this.drawSpeed = 100;
						this.drawSequence = this.generateDrawSequence();

						// 设置目标奖品的索引
						this.targetIndex = this.prize.findIndex(item => item.id === this.presult);

						// 设置目标步数，确保最后一步停在目标奖品上
						this.targetStep = this.drawSequence.length - this.drawSequence.lastIndexOf(this
							.targetIndex) - 1 + 32;

						this.drawInterval = setInterval(() => {
							this.drawStep();
						}, this.drawSpeed);
					} else {
						index.show_tips(res.data.message);
						if(res.data.message == '未在目标群内，无法进行抽奖'){
							this.showerror = true
						}
						if(res.data.message == '未获取到群信息'){
							index.navigate_to('../../pagesC/login/login');
						}
						return
					}
				})

			},
			drawStep() {
				this.drawStepCount++;

				// 更新高亮的奖品
				if (this.drawStepCount - 1 < this.drawSequence.length) {
					this.activeIndex = this.drawSequence[this.drawStepCount - 1];
				}

				// 动画速度逐渐减慢
				if (this.drawStepCount > 15 && this.drawSpeed < 300) {
					this.drawSpeed += 10;
					clearInterval(this.drawInterval);
					this.drawInterval = setInterval(() => {
						this.drawStep();
					}, this.drawSpeed);
				}

				// 停止条件：达到目标步数后停止，并且当前高亮的奖品是目标奖品
				if (this.drawStepCount >= this.targetStep && this.activeIndex === this.targetIndex) {
					this.stopDraw();
				}
			},
			generateDrawSequence() {
				// 生成1→2→4→3→1→2→4→3的循环序列
				const sequence = [];
				let currentIndex = 0;

				for (let i = 0; i < 100; i++) {
					sequence.push(currentIndex);

					// 定义1→2→4→3→1→2→4→3的顺序
					if (currentIndex === 0) {
						currentIndex = 1;
					} else if (currentIndex === 1) {
						currentIndex = 3;
					} else if (currentIndex === 3) {
						currentIndex = 2;
					} else if (currentIndex === 2) {
						currentIndex = 0;
					}
				}

				return sequence;
			},
			stopDraw() {
				clearInterval(this.drawInterval);
				this.isDrawing = false;
				this.getprizeresult()
				// 确保最终停在目标奖品上
				this.activeIndex = this.targetIndex;
				setTimeout(() => {
					this.showprize = true
				}, 500)

			}
		}
	}
</script>

<style>
	@import url("@/static/css/publics.css");
</style>
<style scoped lang="scss">
	page {
		width: 100%;
		height: 100%;
		background-color: #FfF3F3;
	}

	.title {
		font-size: 50rpx;
		color: #FFFFFF;
		margin: auto;
		margin-top: 200rpx;
		width: 80%;
		display: flex;
		align-items: center;
	}

	.tip {
		font-size: 30rpx;
		color: #909399;
		margin: auto;
		margin-top: 100rpx;
		width: 90%;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;

		.t1 {
			font-size: 40rpx;
			font-weight: bold;
			color: #555555;
		}
	}

	.tip2 {
		margin: auto;
		width: 90%;
		margin-top: 10rpx;
		background-color: white;
		padding: 20rpx;
		box-sizing: border-box;
		border-radius: 20rpx;

		.t1 {
			color: #999999;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.t2 {
			margin-top: 10rpx;
			min-height: 40rpx;
			font-size: 30rpx;
			color: #909399;
			display: flex;
			justify-content: space-between;
		}
	}

	.prizedraw {
		margin: 20rpx auto;
		width: 90%;
		height: 500rpx;
		border-radius: 20rpx;
		box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.1);
		background-color: #FFFFFF;
		display: flex;
		justify-content: space-between;
		align-content: space-between;
		flex-wrap: wrap;
		overflow: hidden;
		padding: 30rpx;
		box-sizing: border-box;

		.prize-item {
			width: 47%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			background-color: #f3f4f6;
			padding: 10rpx;
			box-sizing: border-box;
			border-radius: 15rpx;
			transition: all 0.3s ease;
		}

		.active {
			background-color: #fab6b6;
			color: white;
			transform: scale(1.05);
			box-shadow: 0 0 10px rgba(255, 0, 0, 0.5);
		}
	}

	.stbtn {
		width: 50%;
		margin: 40rpx auto;
	}

	.upop {
		color: #666666;
		padding: 40rpx;
		overflow: hidden;
		box-sizing: border-box;
	}

	.smtip {
		margin: auto;
		margin-top: -10rpx;
		font-size: 28rpx;
		color: #666666;
		text-align: center;
	}

	.contain {
		height: 100vh;
		background: linear-gradient(180deg, #fa3534 0%, rgba(245, 245, 245, 1.00) 70%);
		overflow-x: hidden;
		// overflow-y: hidden;
	}
</style>